package com.example.patient.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.example.common.utils.RedisUtils;

import org.springframework.stereotype.Component;

import cn.hutool.http.HttpUtil;

import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;

@Component
public class IdNoUtils {
    
    @Resource
    private RedisUtils redisUtils;

    public Boolean docheck(String idNo, String name){
        String token = getAccessToken();
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/person/idmatch?access_token="+token;
        Map<String, String> body = new HashMap<>();
        body.put("id_card_number", idNo);
        body.put("name", name);
        String strBody = JSON.toJSONString(body);
        String res = HttpUtil.post(url, strBody, -1);

        if(res.isEmpty())
            return false;
        JSONObject jsonObject = JSONObject.parseObject(res);
        int error_code = jsonObject.getIntValue("error_code");
        return error_code == 0;
    }
    
    private String getAccessToken() {
        return getAccessToken("1R4ewG528SMMoPqKEYakFW8e", "XVZOWdXp5ddc8cOw6lufn5Kv4dBidG14", "baidu");
    }

    private String getAccessToken(String appid, String secret, String platform) {
        if (!redisUtils.hasKey(platform + "-" + appid)) {
            return getTokenAndSave(appid, secret, platform);
        }
        return (String) redisUtils.get(platform + "-" + appid);
    }
    
    private JSONObject sendHttp(String appId, String secret) {
        String url = "https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=%s&client_secret=%s";
        String resultString = HttpUtil.get(String.format(url, appId, secret));
        return JSONObject.parseObject(resultString);
    }
    
    private String getTokenAndSave(String appId, String secret, String platform) {
        // 发送获得access_token
        JSONObject jsonObject = sendHttp(appId, secret);
        String accessToken = (String) jsonObject.get("access_token");
        int expiresIn = (int) jsonObject.get("expires_in");
        boolean set = redisUtils.set(platform + "-" + appId, accessToken, expiresIn - 60);
        if (set) {
            return accessToken;
        }
        return "";
    }
}